package com.mo.lib.utils.data;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * @ author：mo
 * @ data：2020/10/16:9:44
 * @ 功能：拼音工具类
 */
public class PinYinUtil {
    public static StringBuilder sb=new StringBuilder();

    /**
     * 获取汉字字符串的各个字首字母
     * 中国：zg
     * @param chines
     * @return
     */
    public static  String getPinYinHeadChar(String chines){
        sb.setLength(0);
        char[] chars=chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat=new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i=0;i<chars.length;i++){
            if(chars[i]>128){
                try{
                    sb.append(PinyinHelper.toHanyuPinyinStringArray(chars[i],defaultFormat)[0].charAt(0));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                sb.append(chars[i]);
            }
        }
        return sb.toString();
    }

    /**
     * 获取汉字字符串的首字母
     * 中国：Z
     * @param string
     * @return
     */
    public static String getPinYinFirstLetter(String string){
        sb.setLength(0);
        char c=string.charAt(0);
        String[] pinyinArray=PinyinHelper.toHanyuPinyinStringArray(c);
        if (pinyinArray!=null){
            sb.append(pinyinArray[0].charAt(0));
        }else{
            sb.append(c);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 获取汉字字符串的汉语拼音
     * 中国：zhongguo
     * @param chines
     * @return
     */
    public static String getPinYin(String chines) {
        sb.setLength(0);
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    sb.append(PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                sb.append(nameChar[i]);
            }
        }
        return sb.toString();
    }
}
